package com.zp.self.module.level_5_设计模式.行为型模式.Ⅷ_迭代器模式;

import lombok.Data;

/**
 * @author ：by Zeng Peng
 * @date ：Created 2022/7/6 7:18
 * @description ：自定义按链表实现顺序集合
 */
public class MyLinkedList<E> implements Collection<E>{

    protected final Node<E> first = new Node<>(null);
    private Node<E> last = first;

    @Override
    public boolean add(E e) {
        Node<E> node = new Node<>(e);
        last.next=node;
        last=node;
        return true;
    }

    @Override
    public boolean remove(E e) {
        Node<E> pro = first;
        while (pro.next!=null){
            if(pro.next.getE().equals(e)){
                pro.next = pro.next.next;
                return true;
            }else
                pro = pro.next;
        }
        return false;
    }

    @Override
    public Iterator<E> getIterater() {
        return new MyIterator();
    }

    @Data
    private  class MyIterator implements Iterator<E> {
        Node<E> current = MyLinkedList.this.first;

        @Override
        public boolean haveNext() {
            return current.next != null;
        }

        @Override
        public  E next() {
            current = current.next;
            return current.getE();
        }
    }

    @Data
    private static class Node<E> {
        public Node( E e) {
            this.e = e;
        }

        private Node<E> next;

        private E e;
    }
}
